﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using Game500.ClientServerCommon.Src;

namespace ClientLauncher.Src
{
  public class ServerConnectionManager
  {
    private readonly IPEndPoint myServerAddress;

    public ServerConnectionManager(IPEndPoint serverAddress)
    {
      myServerAddress = serverAddress;
    }

    public NetworkGameInfo CreateNewGame(string title, Guid mapId)
    {
      var request = new FrontendRequest(title, mapId);
      var info = (NetworkGameInfo)SendRequest(request);
      return info;
    }

    public FrontendInfo GetServerInfo()
    {
      var request = new FrontendRequest();
      var info = (FrontendInfo)SendRequest(request);
      return info;
    }

    private object SendRequest(FrontendRequest request)
    {
      var client = new TcpClient();
      client.Connect(myServerAddress);
      NetworkStream stream = client.GetStream();
      var formatter = new BinaryFormatter();
      formatter.Serialize(stream, request);

      object result = formatter.Deserialize(stream);
      return result;
    }
  }
}